package com.ruoyi.matrix.queue

import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit

/**
 * 分布式锁
 *
 * @author Fatmore
 * @Description FatmoreLock
 * @since 2022/4/5 15:40
 */
@Component("fatmoreLock")
class FatmoreLock(
    private val redisTemplate: StringRedisTemplate
) {
    /**
     * 获得锁
     */
    fun lock(lockId: String, value: String, expireMilli: Long): Boolean {
        return redisTemplate.opsForValue().setIfAbsent(lockId, value, expireMilli, TimeUnit.MILLISECONDS)!!
    }

    fun hasLock(lockId: String): String? {
        val exist = redisTemplate.opsForValue().get(lockId)
        return if (exist == null || "" == exist) {
            null
        } else exist
    }

    fun unlock(lockId: String) {
        redisTemplate.delete(lockId)
    }

    fun increase(key: String): Long {
        val result = redisTemplate.opsForValue().increment(key)
        redisTemplate.expire(key, 7, TimeUnit.DAYS)
        return result!!
    }

    fun increaseWithExpire(key: String, expireDays: Long): Long {
        val result = redisTemplate.opsForValue().increment(key)
        redisTemplate.expire(key, expireDays, TimeUnit.DAYS)
        return result!!
    }

    fun increase(key: String, more: Long): Long {
        val result = redisTemplate.opsForValue().increment(key, more)
        redisTemplate.expire(key, 7, TimeUnit.DAYS)
        return result!!
    }

    /**
     * 获取累增值的当前值
     *
     * @param key
     * @return
     */
    fun getBeforeIncrease(key: String): Long {
        val current = redisTemplate.opsForValue()[key] ?: return 0L
        return current.toLong()
    }

    fun resetForIncrease(key: String) {
        redisTemplate.opsForValue().operations.delete(key)
    }
}